package _7_decorator

//User 用户
type User struct {
	name string
}

//UserRepository 用户资源接口
type UserRepository interface {
	getUser(name string) User
}

//UserRepositoryWithDb db的资源实现
type UserRepositoryWithDb struct {
}

//getUser 模拟从db中获取数据
func (u *UserRepositoryWithDb) getUser(name string) User {
	return User{name: name}
}

//UserRepositoryWithCache 缓存的资源实现
type UserRepositoryWithCache struct {
	cacheStorage map[string]User
}

//getUser 模拟从内存中获取数据
func (u *UserRepositoryWithCache) getUser(name string) User {
	return u.cacheStorage[name]
}

//UserService 用户服务
type UserService interface {
	getUser(name string) User
}

type UserServiceWithDb struct {
	dbRepository UserRepositoryWithDb
}

func (u *UserServiceWithDb) getUser(name string) User {
	return u.dbRepository.getUser(name)
}

type CacheableUserService struct {
	userService     UserService
	cacheRepository UserRepositoryWithCache
}

func NewCacheableUserService() CacheableUserService {
	return CacheableUserService{
		userService:     &UserServiceWithDb{},
		cacheRepository: UserRepositoryWithCache{},
	}
}

func (c *CacheableUserService) getUser(name string) User {
	user := c.cacheRepository.getUser(name)
	if &user != nil {
		return user
	}
	return c.userService.getUser(name)
}
